package com.example.visitedsys.Controller;

import com.example.visitedsys.Aspect.AesUtil;
import com.example.visitedsys.Aspect.Decrypt;
import com.example.visitedsys.Aspect.Encrypt;
import com.example.visitedsys.Shrio.Bean.ActiveUser;
import com.example.visitedsys.Shrio.Bean.ResponseBean;
import com.example.visitedsys.converter.RoleConverter;
import com.example.visitedsys.informationGet.*;
import com.example.visitedsys.pojo.Role;
import com.example.visitedsys.pojo.User;
import com.example.visitedsys.service.RoleService;
import com.example.visitedsys.service.UserService;
import com.example.visitedsys.service.loginLogService;
import com.example.visitedsys.utils.test1;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author  SongPeng
 * @date  2021/10/19 14:22
 * @version 1.0
 */

@RestController
@RequestMapping("/user")
@Api(value="操作员管理")
public class UserController {
    @ModelAttribute
    public void doString(){
        MDC.put("operateModuleName","用户模块");
    }

    private static final Logger logger = LogManager.getLogger(UserController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private loginLogService loginLogService;
    @Autowired
    private RoleService roleService;


    //    @Mylog(value = "用户登录")  //这里添加了AOP的自定义注解

    @Decrypt
    @Encrypt
    @PostMapping ("/login")
    @ApiOperation(value="用户登录")
    @ResponseBody
    public ResponseBean login(@RequestBody User user ,
                              HttpServletRequest request) throws Exception {
//        String userName= AesUtil.decrypt(user.getName(),AesUtil.getKey());
//        String pwd=AesUtil.decrypt(user.getPassword(),AesUtil.getKey());
        logger.info("用户登录"+user.getName());
        String token=userService.login(user.getName(),user.getPassword());
        loginLogService.add(request);
        return ResponseBean.success((Object) token);
    }
    /**
     * 分配角色
     *
     * @param userId
     * @param rids
     */
    @ApiOperation(value = "分配角色", notes = "角色分配给用户")
    @RequiresPermissions({"user:assign"})
    @PostMapping("/{userId}/assignRoles")
    public ResponseBean assignRoles(@PathVariable("userId") Long userId, @RequestBody Long[] rids) {
        logger.info("分配角色");
        userService.assignRoles(Long.valueOf(userId), rids);
        return ResponseBean.success();
    }
    /**
     * 用户具体信息
     * */
    @GetMapping("/info")
//    @RequiresPermissions(logical = Logical.AND, value = {"view"})
    public ResponseBean info() {
        UserInfoGet operatorInfoGet=userService.info();
        return new ResponseBean(200, "用户信息如下", operatorInfoGet);
    }

    @RequestMapping("/401")
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ResponseBean unauthorized() {
        return new ResponseBean(401, "Unauthorized", null);
    }
    /**
     * 删除用户
     *
     * @param userId 用户ID
     * @return
     */
    @RequiresPermissions({"user:delete"})
    @DeleteMapping("/delete/{userId}")
    public ResponseBean delete(@PathVariable("userId") Long userId) {
        logger.info("删除用户");
        userService.deleteById(userId);
        return ResponseBean.success();
    }

    /**
     * 更新状态
     *
     * @param userId
     * @param userStatus
     * @return
     */
    @ApiOperation(value = "用户状态", notes = "禁用和启用这两种状态")
    @RequiresPermissions({"user:update"})
    @PutMapping("/updateStatus/{userId}/{userStatus}")
    public ResponseBean updateStatus(@PathVariable Long userId, @PathVariable Boolean userStatus) {
        userService.updateStatus(userId, userStatus);
        return ResponseBean.success();
    }
    /**
     * 用户密码重置
     *
     * @param userId
     * @return
     */
    @RequiresPermissions({"user:update"})
    @PutMapping("/resetPassword/{userId}")
    public ResponseBean resetPassword(@PathVariable Long userId) {
        logger.info("用户密码重置");
        userService.resetPassword(userId);
        return ResponseBean.success();
    }

    /**
     * 更新用户
     *
     * @param userId
     * @param userEditVO
     * @return
     */
    @RequiresPermissions({"user:update"})
    @PutMapping("/update/{userId}")
    public ResponseBean update(@PathVariable Long userId, @RequestBody @Validated UserEditVO userEditVO) {
        logger.info("用户信息更改");
        userService.update(userId, userEditVO);
        return ResponseBean.success();
    }

    /**
     * 编辑用户
     * @param userId
     * @return
     */
    @RequiresPermissions({"user:update"})
    @GetMapping("/edit/{userId}")
    public ResponseBean edit(@PathVariable Long userId) {
        logger.info("编辑用户");
        UserEditVO userVO = userService.edit(userId);
        return ResponseBean.success(userVO);
    }

    /**
     * 添加用户信息
     * @param userVO
     * @return
     */
    @ApiOperation(value = "添加用户", notes = "添加用户信息")
    @RequiresPermissions({"user:add"})
    @PostMapping("/add")
    public ResponseBean add(@RequestBody @Validated UserVO userVO) {
        userService.add(userVO);
        return ResponseBean.success();
    }
    //查询操作员信息列表
    @GetMapping("/listData")
    @RequiresPermissions({"user"})
    @ResponseBody
    public ResponseBean  listData(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize, UserVO userVO){
        PageVO<UserVO> userList=userService.findUserList(pageNum,pageSize,userVO);
        return ResponseBean.success(userList);
    }

    @ApiOperation(value = "加载菜单", notes = "用户登入后,根据角色加载菜单树")
    @GetMapping("/findMenu")
    public ResponseBean findMenu() {
        List<PermissionNodeVO> menuTreeVOS = userService.findPermission();
        return ResponseBean.success(menuTreeVOS);
    }
    @ApiOperation(value = "已有角色", notes = "根据用户id，获取用户已经拥有的角色")
    @RequiresPermissions({"user:select"})
    @GetMapping("/{userId}/roles")
    public ResponseBean roles(@PathVariable("userId") Long userId) {
        logger.info("用户查询已有角色");
        List<Long> values = userService.roles(Long.valueOf(userId));
        List<Role> list = roleService.findAll();
        //转成前端需要的角色Item
        List<RoleTransferItemVO> items = RoleConverter.converterToRoleTransferItem(list);
        Map<String, Object> map = new HashMap<>();
        map.put("roles", items);
        map.put("values", values);
        return ResponseBean.success(map);
    }
    /**
     * 用户个人中心修改信息
     * */
    @RequiresPermissions({"user:update"})
    @PostMapping("/editSelf")
    public ResponseBean editSelf(@RequestBody UserInfoGet userInfoGet){
        logger.info("当前登录用户更改信息");
        ActiveUser activeUser= (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        Long userId=activeUser.getUser().getUserId();
        User user=new User();
        user.setUserPhone(userInfoGet.getUserPhone());
        user.setUserId(userId);
        userService.editSelf(user);
        return ResponseBean.success();

    }
    /**
     *用户修改密码
     * */
    @RequiresPermissions({"user:add"})
    @PostMapping("/editPassword")
    public ResponseBean editPassword(@RequestParam("password")String password,@RequestParam("newPassword") String newPassword){
        logger.info("当前登录用户更改密码");
        userService.editPassword(password,newPassword);
        return ResponseBean.success();

    }
}
